<?php
namespace Admin\Controller;
use Think\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

class QiniuController extends Controller {

	private $_accessKey;
	private $_secretKey;
	private $_bucket;

	public function __construct(){
		$this->_accessKey = C('qiniu_config')['accessKey'];
		$this->_secretKey = C('qiniu_config')['secretKey'];
		$this->_bucket = C('qiniu_config')['bucket'];
		vendor('Qiniu.autoload');
	}

	//获取token，需要设置一个有效时间，避免反复请求服务器
	public function getToken(){
		$auth = new Auth($this->_accessKey, $this->_secretKey);
  		// 生成上传Token
  		$token = $auth->uploadToken($this->_bucket);
  		return $token;
	}

	//返回token，url
	public function getUpimageInfo(){

		$token = $this->getToken();
		$ret = [
			'status'=>'true',
		    'code'=>'1000',
		    'msg'=>'成功',
		    'data'=>[
		        'token'=>$token, 
		        'url'=>C('qiniu_config')['domain']
		    ]
		];
		return $this->ajaxReturn($ret);
	}

	//获取某一个空间的文件资源
	public function getList(){
		$auth = new Auth($this->_accessKey, $this->_secretKey);
		$bkt = new BucketManager($auth);
		$lst = $bkt->listFiles($this->_bucket);
		return $lst;
	}

	//删除空间文件
	public function delImage($bucket,$key){
		$auth = new Auth($this->_accessKey, $this->_secretKey);
		$bkt = new BucketManager($auth);
		$ret = $bkt->delete($bucket,$key);
		return $ret;
	}


	//上传图片
	public function upload(){
  		
  		$token = $this->getToken();

  		echo $token;
  		exit();

  		$filePath = 'd:/wamp/www/video/Beat.mp4';
  		$key = 'beat.mp4';

		// 初始化 UploadManager 对象并进行文件的上传。
		$uploadMgr = new UploadManager();
		// 调用 UploadManager 的 putFile 方法进行文件的上传。
		list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
  		// 构建 UploadManager 对象

  		//$err->getResponse()->error;//获取错误信息
  		// $err->getResponse()->statusCode;//获取错误code(614表示文件已经存在)
		if($err !== null){
		    var_dump($err);
		}else{
		    var_dump($ret);
		}
	}
}